# -*- coding: UTF-8 -*-
import os
from . import BaseController
from backend.libs import myjson as json
from backend.libs import oss_util as oss
import backend.libs as libs
from urllib.parse import unquote
from uuid import uuid4
from urllib.parse import quote
from settings import TMP_SAVE_VIDEO_FILE_PATH
from datetime import datetime
import time
from voduploadsdk.AliyunVodUtils import *
from voduploadsdk.AliyunVodUploader import AliyunVodUploader
from voduploadsdk.UploadVideoRequest import UploadVideoRequest 

class UploadImageController(BaseController):

    SUPPORT_IMAGE_TYPES = ('image/jpg', 'image/png', 'image/gif', 'image/jpeg')
    SUPPORT_IMAGE_MAX_SIZE = 500<<12

    def post(self):
        print("*" * 20)
        print('开始上传图片文件')
        index = self.get_argument('index', '')
        field = self.get_argument('field', '')
        if len(self.request.files['file']) == 0:
            return self.render_json_code_999(msg='请上传图片')

        for f in self.request.files['file']:
            fname, content_type, fbody = f['filename'], f['content_type'], f['body']
            if content_type.lower() not in self.SUPPORT_IMAGE_TYPES:
                return self.render_json_code_999(msg="只支持JPG、PNG、GIF 图片格式")
            if len(fbody) > self.SUPPORT_IMAGE_MAX_SIZE:
                return self.render_json_code_999(msg="最大支持512KB")
            
            filename = libs.auto_uuid()
            fname_arr = fname.split('.')
            if len(fname_arr) > 1:
                filename = filename + "." + fname_arr[len(fname_arr) - 1]
            print('开始上传图片文件：%s ' % filename)
            oss.upload(filename, fbody)
            url = "https://media.joyfulmedia.cn/" + filename
                    
            return self.render_json(data={'url':url,'index':index, 'field': field})


class UploadVideoController(BaseController):

    SUPPORT_MAX_FILE_SIZE = 310658240

    # 测试上传本地视频
    def uploadLocalVideo(self, filePath, filename):
        try:
            uploader = AliyunVodUploader('LTAIjzYMUkyGRdpq', 'sTbvM6C50e5Nk69Wn2T3QuPauACuGB')
            uploadVideoRequest = UploadVideoRequest(filePath, filename)
            # 可以设置视频封面，如果是本地或网络图片可使用UploadImageRequest上传图片到点播，获取到ImageURL
            #uploadVideoRequest.setCoverURL('https://sample.com/sample.jpg')  
            #uploadVideoRequest.setTags('test1,test2')
            video_id = uploader.uploadLocalVideo(uploadVideoRequest)
            print("file: %s, video_id: %s" % (filePath, video_id))
            return video_id
        except AliyunVodException as e:
            print(e)
        return None

    def post(self):
        print('come here ..........')
        filetype = self.get_argument('type', '1')   
        index = self.get_argument('index', '')
        field = self.get_argument('field', '')

        if len(self.request.files['file']) == 0:
            return self.render_json(code=-1, msg='视频文件不能为空')

        # 验证文件格式和大小
        upload_file = self.request.files['file'][0]
        filename, filebody = quote(upload_file['filename']), upload_file['body']
        if len(filebody) > self.SUPPORT_MAX_FILE_SIZE:
            return self.render_json(code=-1, msg="最大支持104MB")

        uuid = uuid4().hex
        print('%s|开始上传: %s' % (uuid, filename))
        suffix = filename[filename.rfind('.'):]

        new_file_name = uuid + suffix
        tmppath = TMP_SAVE_VIDEO_FILE_PATH +"/" + new_file_name

        with open(tmppath, 'wb+') as destination:
            destination.write(filebody)

        src_url = self.uploadLocalVideo(tmppath, '%s_%s' % (uuid, filename))
        # oss.upload(filename, None, tmppath)
        # url = "https://media.joyfulmedia.cn/" + filename
        data = {'url': src_url}

        # 删除临时文件
        os.remove(tmppath)

        return self.render_json(msg='上传成功', data=data)

